#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import <UIKit/UIKit.h>
#import <UIKit/UIApplication.h>
#import <Preferences/PSSpecifier.h>
#import <LockInfo/Plugin.h>

#import "framework/FWCommon.h"
#import "framework/FWApplication.h"

#import "PICommon.h"
#import "PITaskIntegration.h"
#import "PITaskStatus.h"
#import "PIContext.h"
#import "PIPlugin.h"

#import "PITaskContextPrefs.h"


static NSString* const kContextKey = @"contextKey";


@implementation PITaskContextPrefs

@synthesize contexts;


// ******************************************************************************************
#pragma mark -
#pragma mark Initialisation and object management

- (id)initForContentSize:(CGSize)contentSize
{
	DebugLog(@"LI:PICommon: initForContentSize ##########################################");
    
    [_specifiers release];
    _specifiers = nil;
    [contexts release];
    
    if ([super respondsToSelector:@selector(initForContentSize:)])
        self = [super initForContentSize:contentSize];
    else
        self = [super init];
    
    return self;
}

- (void)dealloc
{
	DebugLog(@"LI:PICommon: dealloc ##########################################");
    
    [_specifiers release];
    _specifiers = nil;
    [contexts release];
    
    [super dealloc];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Get switch state

- (CFBooleanRef)stateForSpecifier:(PSSpecifier*)spec
{
    NSString* item = [spec propertyForKey:kContextKey];
    NSString* key = [self.specifier.properties valueForKey:@"defaults"];
    [spec.properties setValue:key forKey:@"defaults"];

    if (!self.contexts) {
        NSArray* items = (NSArray*)CFPreferencesCopyAppValue((CFStringRef)kPITaskOptionsDefaultContexts, (CFStringRef)key);
        self.contexts = items ? [NSMutableArray arrayWithArray:items] : [NSMutableArray arrayWithCapacity:10];
        [items release];
    }
    
    DebugLog(@"LI:PICommon: Getting value for %@, item=%@, key=%@, contexts=%@", spec.name, item, key, self.contexts);
    
    return [self.contexts indexOfObject:item] == NSNotFound ? kCFBooleanFalse : kCFBooleanTrue;
}


// ******************************************************************************************
#pragma mark -
#pragma mark Get list of Tags

- (void)setState:(CFBooleanRef)show forSpecifier:(PSSpecifier*)spec
{
    DebugLog(@"LI:PICommon: set %@ value %@", spec, show);
    
    NSString* key = [spec propertyForKey:@"defaults"];
    NSString* item = [spec propertyForKey:kContextKey];
    
    if (!self.contexts)
        self.contexts = [NSMutableArray arrayWithCapacity:10];
    
    if (CFBooleanGetValue(show)) {
        if ([contexts indexOfObject:item] == NSNotFound)
            [contexts addObject:item];
    }
    else {
        NSInteger idx = [contexts indexOfObject:item];
        if (idx != NSNotFound)
            [contexts removeObjectAtIndex:idx];
    }
    
    DebugLog(@"LI:PICommon: Key %@", key);
    DebugLog(@"LI:PICommon: Contexts %@", contexts);
    
    CFPreferencesSetAppValue((CFStringRef)kPITaskOptionsDefaultContexts, contexts, (CFStringRef)key);

    // Update instance counter
    Boolean exists;
    CFIndex count = CFPreferencesGetAppIntegerValue((CFStringRef)kPITaskOptionsDefaultContextsUpdates, (CFStringRef)key, &exists);
    CFPreferencesSetAppValue((CFStringRef)kPITaskOptionsDefaultContextsUpdates, (CFNumberRef)[NSNumber numberWithLong:count + 1], (CFStringRef)key);
    
    CFPreferencesAppSynchronize((CFStringRef)key);
}


// ******************************************************************************************
#pragma mark -
#pragma mark Get list of tags

- (NSArray *)specifiers
{
    if (_specifiers == nil) {
        NSArray* dbContexts = [NSArray array];
        
        UIPasteboard* pasteBoard = [UIPasteboard pasteboardWithName:kPIStatusPasteboard create:NO];
        NSString* dbPath = FWStringValueFromPasteboard(pasteBoard, kPIPasteboardDBPath);
        NSNumber* dbVers = FWNumberValueFromPasteboard(pasteBoard, kPIPasteboardDBVersion);

        if (dbPath && dbVers) {
            FWApplication* app = [[FWApplication alloc] init];
            app.databasePath = dbPath;
            app.fwPlugin = [[[PIPlugin alloc] initWithPIVersion:dbVers.integerValue] autorelease];
            
            dbContexts = [PITaskIntegration arrayOfContexts:app earliest:nil counts:NO];
            [app release];
        }
        
        NSMutableArray* specifiers = [NSMutableArray arrayWithCapacity:contexts.count];

        for (PIContext* context in dbContexts) {
            
            PSSpecifier* ps = [PSSpecifier preferenceSpecifierNamed:context.title                                                                     
                                                             target:self
                                                                set:@selector(setState:forSpecifier:)
                                                                get:@selector(stateForSpecifier:)
                                                             detail:Nil
                                                               cell:PSSwitchCell
                                                               edit:Nil];
            [ps setProperty:[[NSNumber numberWithInt:context.key] stringValue] forKey:kContextKey];
            
            [specifiers addObject:ps];
        }
        
        _specifiers = [specifiers retain];
        
        self.contexts = nil;
    }
    
    return _specifiers;
}

@end
